const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate, todoUpdateSchema } = require('../../../lib/validation');

async function handler(req, res) {
  const { id } = req.query;

  if (!id || isNaN(parseInt(id))) {
    return res.status(400).json({
      success: false,
      message: '无效的待办ID'
    });
  }

  try {
    switch (req.method) {
      case 'GET':
        return await getTodoById(req, res, parseInt(id));
      case 'PUT':
        return await updateTodo(req, res, parseInt(id));
      case 'DELETE':
        return await deleteTodo(req, res, parseInt(id));
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('待办详情API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取待办详情
async function getTodoById(req, res, todoId) {
  const todos = await query(
    'SELECT * FROM todos WHERE id = ? AND user_id = ?',
    [todoId, req.user.id]
  );

  if (todos.length === 0) {
    return res.status(404).json({
      success: false,
      message: '待办不存在'
    });
  }

  res.status(200).json({
    success: true,
    data: todos[0]
  });
}

// 更新待办
async function updateTodo(req, res, todoId) {
  // 检查待办是否存在且属于当前用户
  const existingTodos = await query(
    'SELECT * FROM todos WHERE id = ? AND user_id = ?',
    [todoId, req.user.id]
  );
  
  if (existingTodos.length === 0) {
    return res.status(404).json({
      success: false,
      message: '待办不存在'
    });
  }

  const existingTodo = existingTodos[0];

  // 验证请求数据
  const validation = validate(todoUpdateSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const updateData = validation.data;
  const updateFields = [];
  const updateValues = [];

  // 构建更新字段
  Object.keys(updateData).forEach(key => {
    if (updateData[key] !== undefined) {
      updateFields.push(`${key} = ?`);
      updateValues.push(updateData[key]);
    }
  });

  // 如果状态更新为已完成，记录完成时间
  if (updateData.status === 'completed' && existingTodo.status !== 'completed') {
    updateFields.push('completed_at = CURRENT_TIMESTAMP');
  }

  // 如果状态从已完成改为其他状态，清除完成时间
  if (updateData.status && updateData.status !== 'completed' && existingTodo.status === 'completed') {
    updateFields.push('completed_at = NULL');
  }

  if (updateFields.length === 0) {
    return res.status(400).json({
      success: false,
      message: '没有需要更新的字段'
    });
  }

  updateValues.push(todoId);

  const updateSql = `UPDATE todos SET ${updateFields.join(', ')} WHERE id = ?`;
  await query(updateSql, updateValues);

  // 查询更新后的待办
  const updatedTodo = await query('SELECT * FROM todos WHERE id = ?', [todoId]);

  res.status(200).json({
    success: true,
    message: '待办更新成功',
    data: updatedTodo[0]
  });
}

// 删除待办
async function deleteTodo(req, res, todoId) {
  // 检查待办是否存在且属于当前用户
  const existingTodos = await query(
    'SELECT * FROM todos WHERE id = ? AND user_id = ?',
    [todoId, req.user.id]
  );
  
  if (existingTodos.length === 0) {
    return res.status(404).json({
      success: false,
      message: '待办不存在'
    });
  }

  // 删除待办
  await query('DELETE FROM todos WHERE id = ?', [todoId]);

  res.status(200).json({
    success: true,
    message: '待办删除成功'
  });
}

export default authenticateToken(handler);